import {
  CallHandler,
  ExecutionContext,
  Injectable,
  Logger,
  NestInterceptor,
} from '@nestjs/common';
import { Observable, tap } from 'rxjs';
import { Request } from 'express';

@Injectable()
export class InvokeRecordInterceptor implements NestInterceptor {
  private readonly logger = new Logger();
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest<Request>();
    const userAgent = request.headers['user-agent'];
    const { ip, method, path } = request;
    this.logger.debug(
      `[${method}] ${path}${ip}  ${userAgent} :${context.getClass().name} ${context.getHandler().name} `,
    );
    this.logger.debug(`user:${request.user?.id},${request.user?.username}`);
    const now = Date.now();
    return next.handle().pipe(
      tap((res) => {
        const response = context.switchToHttp().getResponse();
        const { statusCode } = response;
        const responseTime = Date.now() - now;
        this.logger.debug(
          `[${method}] ${path}${ip}  ${userAgent} : ${statusCode} : ${responseTime}ms`,
        );
        this.logger.debug(`Response:${JSON.stringify(res)}`);
      }),
    );
  }
}
